package com.dingding.common.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

/**
 * @ClassName: HttpTool
 * @Description: http请求工具
 * @author fengshuonan
 * @date 2016年1月26日 下午4:47:26
 */
public class HttpTool {
	
	private static Logger log = Logger.getLogger(HttpTool.class);
	
	/**
	 * @Description: 请求一个url获取到JSONObject
	 * @author fengshuonan
	 */
	public static JSONObject loadJson(String url) {
		String jsonString = HttpTool.requestUrl(url);
		JSONObject jsonObject = JSONUtil.parseObject(jsonString);
		return jsonObject;
	}
	
	/**
	 * @Title: postXml
	 * @Description: 向指定url 用post方式发送一段xml信息
	 * @param url 要post的地址
	 * @param xmlStr post的xml信息
	 * @author fengshuonan
	 * @return String 服务器返回的信息
	 * @throws
	 */
	public static String postXml(String url,String xmlStr){
		return HttpTool.postUrlString(url, xmlStr);
	}
	
	
	/**
	 * @Description: 向某个url发送post请求，请求内容为json
	 * @author fengshuonan
	 * @return String
	 */
	public static JSONObject postJsonGetJson(String url,String json){
		return JSONUtil.parseObject(HttpTool.postUrlString(url, json));
	}
	
	
	/**
	 * @Description: 向某个url post一段字符串信息
	 * @param url 被请求的地址
	 * @param str 被post的内容
	 * @author fengshuonan
	 * @return String
	 */
	private static String postUrlString(String url, String str) {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);

		HttpEntity entity = null;
		HttpResponse response = null;
		
		try {
			entity = new StringEntity(str);
			httpPost.setEntity(entity);
			response = client.execute(httpPost);
			InputStream inputStream = response.getEntity().getContent();
			return ToolUtil.readStreamToText(inputStream);
			
		} catch (Exception e) {
			log.error("http请求"+url+"时候出现错误！HttpTool:postUrlString()",e);
		}finally{
			try {
				if(client != null){
					client.close();
				}
			} catch (IOException e) {
				log.error("http请求"+url+"时候出现错误！HttpTool:postUrlString()",e);
			}
		}
		return "";
	}
	
	/**
	 * @Description: 获取请求某个url地址后的数据
	 * @param url 被请求的网址
	 * @author fengshuonan
	 * @throws
	 */
	public static String requestUrl(String url){
		StringBuilder json = new StringBuilder();
		BufferedReader reader = null;
        try {
            URL addr = new URL(url);
            URLConnection connection = addr.openConnection();
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine = null;
            while ( (inputLine = reader.readLine()) != null) {
                json.append(inputLine);
            }
            return json.toString();
        } catch (MalformedURLException e) {
        	log.error("获取请求某个url地址后的数据，出现异常！HttpTool : getRequestJson()",e);
        	return "{\"code\":40000,\"text\":\"系统异常\"}";
        } catch (IOException e) {
        	log.error("获取请求某个url地址后的数据，出现异常！HttpTool : getRequestJson()",e);
        	return "{\"code\":40000,\"text\":\"系统异常\"}";
        } finally {
        	if(reader != null){
        		try {
    				reader.close();
    			} catch (IOException e) {
    				log.error("获取请求某个url地址后的数据，出现异常！HttpTool : getRequestJson()",e);
    			}
        	}
        }
	}
	
	/**
	 * @Description:发送一个post的form请求
	 * @param url 请求的url
	 * @param params 请求的参数集合
	 * @author fengshuonan
	 * @since 2.4
	 */
	public static String postForm(String url,Map<String,String> map){
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		HttpEntity entity = null;
		HttpResponse response = null;
		
		ArrayList<NameValuePair> arrayList = new ArrayList<NameValuePair>();
		for(Map.Entry<String, String> entry : map.entrySet()){
			arrayList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		
		try {
			entity = new UrlEncodedFormEntity(arrayList);
			httpPost.setEntity(entity);
			response = client.execute(httpPost);
			InputStream inputStream = response.getEntity().getContent();
			return ToolUtil.readStreamToText(inputStream);
		} catch (Exception e) {
			log.error("http请求"+url+"时候出现错误！HttpTool:postUrlString()",e);
		}finally{
			try {
				if(client != null){
					client.close();
				}
			} catch (IOException e) {
				log.error("http请求"+url+"时候出现错误！HttpTool:postUrlString()",e);
			}
		}
		return "";
	}
	
	/**
	 * @Description:发送一次post请求并自定义请求头
	 * @author fengshuonan
	 * @since 2.4
	 */
	public static String postSelfHeaderString(String url,String json,String time){
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);

		HttpEntity entity = null;
		HttpResponse response = null;
		
		String auth = Base64Util.encode("did002" + ":" + time);

		BasicHeader header1 = new BasicHeader("Accept","application/json");
		BasicHeader header2 = new BasicHeader("Content-Type","application/json;charset=utf-8");
		BasicHeader header3 = new BasicHeader("Authorization",auth);
		httpPost.setHeaders(new Header[]{header1,header2,header3});
		
		try {
			entity = new StringEntity(json);
			httpPost.setEntity(entity);
			response = client.execute(httpPost);
			InputStream inputStream = response.getEntity().getContent();
			return ToolUtil.readStreamToText(inputStream);
			
		} catch (Exception e) {
			log.error("http请求"+url+"时候出现错误！HttpTool:postUrlString()",e);
		}finally{
			try {
				if(client != null){
					client.close();
				}
			} catch (IOException e) {
				log.error("http请求"+url+"时候出现错误！HttpTool:postUrlString()",e);
			}
		}
		return "";
	}
	
	/**
	 * @Description: 请求一个url获取一个json，并且自定义返回json的编码
	 * @author fengshuonan
	 * @since 2.4
	 */
	public static JSONObject loadJson(String url,String encode){
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		HttpResponse response = null;
		try {
			response = client.execute(httpPost);
			InputStream inputStream = response.getEntity().getContent();
			return JSONUtil.parseObject(ToolUtil.readStreamToText(inputStream,encode));
		} catch (Exception e) {
			log.error("http请求"+url+"时候出现错误！HttpTool:postUrlString()",e);
		}finally{
			try {
				if(client != null){
					client.close();
				}
			} catch (IOException e) {
				log.error("http请求"+url+"时候出现错误！HttpTool:postUrlString()",e);
			}
		}
		return null;
	}
}
